package org.elephas.webapp.application.security;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.elephas.model.Blog;
import org.elephas.model.BlogRole;
import org.elephas.webapp.application.ElephasSession;
import org.elephas.webapp.frontend.page.blog.BlogBasePage;

public class ElephasAuthorizationStrategy implements IAuthorizationStrategy {

	public boolean isActionAuthorized(Component component, Action action) {
		BlogRole desiredRole = getDesiredRole(component, action);
		if (desiredRole == null) {
			// no AuthorizeAction annotation present
			return true;
		}
		BlogRole role = getBlogRoleForCurrentUser(component);
		return role != null && role.implies(desiredRole);
	}

	@SuppressWarnings("unchecked")
	public boolean isInstantiationAuthorized(Class componentClass) {
		return true;
	}

	private BlogRole getBlogRoleForCurrentUser(Component component) {
		Page page = component.getPage();
		Blog blog = null;
		if (page instanceof BlogBasePage) {
			blog = ((BlogBasePage) page).getBlog();
		}
		return ElephasSession.get().getUserRole(blog);
	}

	private BlogRole getDesiredRole(Component component, Action action) {
		Class<? extends Component> c = component.getClass();
		AuthorizeAction aa = c.getAnnotation(AuthorizeAction.class);
		if (aa == null) {
			return null;
		}
		if (action.getName().equals(aa.action())) {
			return aa.role();
		}
		return null;
	}
}
